package com.aircms.interceptor;

import com.aircms.common.ServerResponse;
import com.aircms.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InterceptorAdmin implements HandlerInterceptor {

    private static final Logger logger=LoggerFactory.getLogger(InterceptorAdmin.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("Authorization");
        response.setCharacterEncoding("UTF-8"); //设置编码格式
        response.setContentType("text/json");   //设置数据格式
        if(token!=null){
            String id=JwtUtil.parserJwt(token,"id");
            if(id=="false"){
                ServerResponse serverResponse=ServerResponse.resResponse("",-100);  // token失效或非法
                // 对象转json
                ObjectMapper objectMapper=new ObjectMapper();
                response.getWriter().append(objectMapper.writeValueAsString(serverResponse));
                return false;
            }
            return true;
        }else {
            ServerResponse serverResponse=ServerResponse.resResponse("",-101);      // token不能为空
            // 对象转json
            ObjectMapper objectMapper=new ObjectMapper();
            response.getWriter().append(objectMapper.writeValueAsString(serverResponse));
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}
